using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Helpers;
using AvalonAdmin.Pages.Rule.Views.RuleMapping;
using AvalonAdminDto.Common;

using AvalonAdminDto.Rule.RuleMappingDtos;
using D.UtilCore.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.Rule.ViewModels.RuleMapping
{
    /// <summary>
    /// 规则映射查询视图模型
    /// </summary>
    public class RuleMappingQueryViewModel : SimpleIntegratedViewModel<RepRuleMapping>
    {
        #region 构造函数

        private readonly string? _type;
        private readonly string? _ruleId;

        public RuleMappingQueryViewModel(string? type = null, string? ruleId = null)
        {
            _type = type;
            _ruleId = ruleId;
            LoadData();
        }

        #endregion

        #region 查询条件属性

        private string? _name;
        /// <summary>
        /// 映射名称
        /// </summary>
        public string? Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }

        #endregion

        #region 事件和选择相关
        
        private RepRuleMapping? _repRuleMapping;
        
        // 事件
        public event InformationRequestedHandler InformationRequested;
        protected async void Submit(object? obj)
        {
            List<RepRuleMapping> listRuleMapping = JsonConvert.DeserializeObject<List<RepRuleMapping>>(JsonConvert.SerializeObject(obj));
            if (listRuleMapping.FindAll(a => a.IsSelected == true).Count() > 1)
            {
                ShowError("只能选择一个");
                return;
            }
            if (listRuleMapping.FindAll(a => a.IsSelected == true).Count() == 0)
            {
                ShowError("请选择一个");
                return;
            }
            _repRuleMapping = listRuleMapping.FirstOrDefault(a => a.IsSelected == true);
            InformationRequested?.Invoke(this, new InformationEventArgs<RepRuleMapping>(_repRuleMapping));
        }
        
        #endregion

        #region 重写基类方法

        /// <summary>
        /// 重置查询条件
        /// </summary>
        protected void ResetQuery()
        {
            Name = string.Empty;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public override async Task<IEnumerable<RepRuleMapping>> QueryAsync()
        {
            var queryParams = new
            {
                RuleId = _ruleId,
                Name,
                PageSize,
                PageNo
            };

            var res = await HttpHelper<PageModel<RepRuleMapping>>.PostAsync(ApiUrl.QueryRuleMappingPages, queryParams);
            if (res.Code == StatusCodeEnum.OK && res.Data != null)
            {
                TotalCount = (int)res.Data.TotalCount;
                return res.Data.Data;
            }
            else
            {
                ShowError(res.Msg ?? "查询失败");
                return new List<RepRuleMapping>();
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        public override async Task AddAsync(RepRuleMapping? item = null)
        {
            var res = await Dialog.ShowModal<Page_RuleMapping_Modify, RuleMappingModifyViewModel>(
                new RuleMappingModifyViewModel(ruleId: _ruleId, viewStatus: ViewStatus.Add),
                null, 
                options: GetDialogOptions("新增规则映射"));
            
            if (res == DialogResult.OK)
            {
                await LoadDataAsync();
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        public override async Task UpdateAsync(RepRuleMapping? item = null)
        {
            var target = item ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要修改的数据");
                return;
            }

            var res = await Dialog.ShowModal<Page_RuleMapping_Modify, RuleMappingModifyViewModel>(
                new RuleMappingModifyViewModel(target.Id, _ruleId, ViewStatus.Edit),
                null,
                options: GetDialogOptions("修改规则映射"));
            
            if (res == DialogResult.OK)
            {
                await LoadDataAsync();
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        public override async Task DeleteAsync(RepRuleMapping? item = null)
        {
            var target = item ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var messageBoxResult = await MessageBox.ShowOverlayAsync(
                "确认删除该规则映射吗？", 
                "提示", 
                icon: MessageBoxIcon.Question, 
                button: MessageBoxButton.OKCancel);
            
            if (messageBoxResult == MessageBoxResult.OK)
            {
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteRuleMapping}/{target.Id}");
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess(res.Msg ?? "删除成功");
                    await LoadDataAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "删除失败");
                }
            }
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        public override async Task BatchDeleteAsync(IEnumerable<RepRuleMapping>? items = null)
        {
            var targets = items ?? Data?.Where(m => m.IsSelected);
            if (targets == null || !targets.Any())
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var messageBoxResult = await MessageBox.ShowOverlayAsync(
                "确认删除选中的规则映射吗？", 
                "提示", 
                icon: MessageBoxIcon.Question, 
                button: MessageBoxButton.OKCancel);
            
            if (messageBoxResult == MessageBoxResult.OK)
            {
                var ids = targets.Select(m => m.Id).ToList();
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteRuleMapping}/{string.Join(",", ids)}");
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess(res.Msg ?? "删除成功");
                    await LoadDataAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "删除失败");
                }
            }
        }

        protected override bool GetIsSelected(RepRuleMapping item)
        {
            return item.IsSelected;
        }

        protected override void SetIsSelected(RepRuleMapping item, bool isSelected)
        {
            item.IsSelected = isSelected;
        }
        
        #endregion
    }
}



